package com.cqut.forum.security;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.cqut.forum.util.CookieHandler;
import com.cqut.forum.util.DefaultElements;
  
 
public class SessionFilter implements HandlerInterceptor {

    private String ignore_method;
    private String jump_method;
    private String[] ignore_methods;

	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub

	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
        StringBuilder url=new StringBuilder(request.getRequestURL());
        url.append("?");
        Enumeration<String> enu=request.getParameterNames();
        while(enu.hasMoreElements()){
        	 String d= enu.nextElement();
        	 url.append(d).append("=").append(request.getParameter(d)).append("&");
        }
        String urlstr=null;
        if(url.charAt(url.length()-1)=='&'||url.charAt(url.length()-1)=='?'){
        	urlstr=url.substring(0, url.length()-1);
        }

        // 是否过滤
     	boolean doFilter = true;
     	for (String s : ignore_methods) {
     		if (url.toString().contains(s)) {
     			// 如果uri中包含不过滤的uri，则不进行过滤
     			doFilter = false;
     			break;
     		}
     	}
     	if (doFilter) {
     		String cookieValue=CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME);
     		if(null==cookieValue||"".equals(cookieValue)){
     		   request.setAttribute("url",urlstr );
     		   request.getRequestDispatcher(jump_method).forward(request, response);
     		   return false;  
     		}else{
     			return true;
     		}
     	}
//     	response.sendRedirect(outTimePageUrl); // 返回提示页面  
     	return true;
	}

	public String getIgnore_method() {
		return ignore_method;
	}

	public void setIgnore_method(String ignore_method) {
		this.ignore_method = ignore_method;
		this.ignore_methods=ignore_method.trim().split(",");
	}

	public String[] getIgnore_methods() {
		return ignore_methods;
	}

	public void setIgnore_methods(String[] ignore_methods) {
		this.ignore_methods = ignore_methods;
	}

	public String getJump_method() {
		return jump_method;
	}

	public void setJump_method(String jump_method) {
		this.jump_method = jump_method;
	}

}